package com.example.cloudzuul.demos.web;

import com.netflix.zuul.ZuulFilter;
        import com.netflix.zuul.context.RequestContext;
        import org.springframework.stereotype.Component;

        import javax.servlet.http.HttpServletRequest;

//@Component
public class AccessFilter extends ZuulFilter {
    public String filterType() {
        return "pre"; //前置过滤器
    }
    public int filterOrder() {
        return 0; //优先级，数字越大，优先级越低
    }
    public boolean shouldFilter() {
        return true; //是否执行该过滤器，true代表需要过滤
    }
    public Object run() {
        // 请求上下文对象  =>  LocalThread 本地线程对象
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取当前的请求对象
        HttpServletRequest request = ctx.getRequest();
        //获取传来的参数accessToken
        Object accessToken = request.getParameter("accessToken");
        if(accessToken == null) {
            System.out.println("access token is empty");
            //过滤该请求，不往下级服务去转发请求，到此结束
            ctx.setSendZuulResponse(false);
            // 设置响应码
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");
            return null;
        }
        //如果有token，则进行路由转发, 这里return的值没有意义，zuul框架没有使用该返回值
        return null;
    }
}


